from django.shortcuts import render,HttpResponse,reverse
from django.contrib.auth.hashers import make_password, check_password
from . import models
import os,time


# 后台模板首页
def index(request):
    return render(request,'myadmin/index.html')
# 用户添加
def useradd(request):
   # 判断用户提交数据的方式
    if request.method == 'GET':
        # GET请求返回网页
        return render(request,'myadmin/user/useradd.html')
    # POST请求接收数据保存到数据库
    elif request.method == 'POST':
        # 获取数据转成字典类型
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        # 对用户的密码进行加密
        data['password'] = make_password(data['password'],None,'pbkdf2_sha256')
        # 如果用户上传了头像
        myfile = request.POST.get('pic_url')

        if myfile:
            data['pic_url'] = upload(myfile)






def upload(myfile):
    filename = str(time.time()) + "." + myfile.name.split('.').pop()
    f = open("./static/pics/" + filename, "wb+")
    for chunk in myfile.chunks():  # 分块写入文件
        f.write(chunk)
    f.close()
    return '/static/pics/'+filename






